<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 红包
 */
namespace app\allwin\model;
use app\allwin\model\AllwinUnmarket;
use app\allwin\model\AllwinUnmarketOrder;
use app\common\facade\WechatPay;
use app\common\model\SystemMemberMiniapp;
use think\Model;
use util\Util;

class AllwinUnmarketReward extends Model{

    protected $pk = 'id';
    
   //和主用户表绑定关系
    public function user(){
        return $this->hasOne('app\common\model\SystemUser','id','uid');
    }

    //活动主表
    public function unmarket(){
        return $this->hasOne('AllwinUnmarket','id','union_id');
    }

    //添加或编辑
    public static function edit(array $param){
        $rel = self::where(['uid' => $param['uid'],'union_id' => $param['union_id']])->find();
        if(isset($rel)){
            $rel->money          = ['inc',money($param['money'])];  
            $rel->update_time    = time();
            return $rel->save();
        }else{
            $data = [
                'member_miniapp_id' => trim($param['member_miniapp_id']),
                'uid'               => trim($param['uid']),
                'union_id'          => trim($param['union_id']),
                'money'             => trim(money($param['money'])),
                'times'             => time(),
            ];
            return self::insert($data);
        }
    }

    /**红包奖励与付款给客户 */
    public static function  redRacket($order){
        $redpack_amount = 0;
        if($order->share_uid > 0){
            $market = AllwinUnmarket::where(['id' => $order->share_id])->field('id,uid,member_miniapp_id,title,share_text,price,bonus_types,bonus_user_types,share_ratio,share_ratio_user')->find();
            if(!$market->isEmpty()){
                $share_ratio = 0;
                if($market->bonus_user_types){
                    //判断奖励用户是否下单
                    $is_order = AllwinUnmarketOrder::where(['share_id' => $order->share_id,'uid' => $order->share_uid,'state' => 1])->count();
                    if($market->bonus_user_types == 1){
                        $share_ratio = $is_order > 0 ? $market->share_ratio_user : 1;
                    }else{
                        $share_ratio = $is_order > 0 ? $market->share_ratio_user : $market->share_ratio;
                    }
                }else{
                    $share_ratio = $market->share_ratio;
                }
                //开始计算奖励金额
                $amount = 0;
                if($share_ratio >= 1){
                    if($market->bonus_types){
                        $amount = $share_ratio;
                    }else{
                        $money  = Util::priceCalculate($order['price'],'*',$order->price*($share_ratio/100));
                        $money  = $money >= 1 ? $money : 1;
                        $num    = intval($money/2);
                        $num    = $num > 0 ? $num : 1;
                        $amount = pocket($money,$num,1);
                    }
                }
                if($amount > 0){
                    $wechat = model('SystemUser')->where(['id' => $order->share_uid])->field('official_uid,invite_code')->find();
                    if($wechat->isEmpty()){
                        return $redpack_amount;
                    }
                    $web = SystemMemberMiniapp::where(['id' => $market->member_miniapp_id])->find();
                    $payment = WechatPay::doPay($market->member_miniapp_id,true);
                    $redpackData = [
                        'mch_billno'   => $wechat->invite_code.order_no(),
                        'send_name'    => $web->appname,
                        're_openid'    => $wechat->official_uid,
                        'total_num'    => 1,
                        'total_amount' => $amount*100,
                        'wishing'      => '继续~努力完成更多任务',
                        'act_name'     => $web->appname.'联盟活动',
                        'remark'       => $market->share_text,
                    ];
                    $result = $payment->redpack->sendNormal($redpackData); 
                    if ($result['return_code'] === 'SUCCESS') {
                        if ($result['result_code'] === 'SUCCESS') {
                            $redpack_amount = $amount;
                            self::money($market->member_miniapp_id,$market->id,$order->share_uid,$redpack_amount); //增加钱
                        }
                    }
                }
            }
        }
        return $redpack_amount;
    }

    /**
     * 应付款增加
     * @param integer $miniapp_id
     * @param integer $uid
     * @param integer $money (元)
     * @return void
     */
    public static function money(int $miniapp_id,int $union_id,int $uid,float $money){
        $info  = self::where(['uid' => $uid,'union_id' => $union_id])->find();
        $money = money($money);
        if(empty($info)){
            $data['member_miniapp_id'] = $miniapp_id;
            $data['union_id']          = $union_id;
            $data['uid']               = $uid;
            $data['money']             = $money;
            $data['number']            = 1;
            $data['update_time']       = time();
            return self::insert($data);
        }else{
            $info->number         = ['inc',1];
            $info->money          = ['inc',$money];
            $info->update_time    = time();
            return $info->save();
        }
    }
}